using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebControls;

namespace RGB.SharePoint.Util.SPExtendedImageField
{

	public class SPExtendedImageFieldControl : BaseFieldControl
	{
		// Path of the picture
		private HiddenField hfPath;

		public SPExtendedImageFieldControl(SPExtendedImageField parentField) { }

		public override object ItemFieldValue
		{
			get
			{
				return base.ItemFieldValue;
			}
			set
			{
				// Set the value on which that is contained in the hidden field
				base.ItemFieldValue = hfPath.Value;
			}
		}

		protected override void CreateChildControls()
		{

			base.CreateChildControls();

			// Hold the ID of the field
			Guid guid = Field.Id;

			// Create the hidden field
			hfPath = new HiddenField { ID = "hfPath" + guid };

			// Get the value of the field 
			if (ItemFieldValue != null)
				hfPath.Value = (string)ItemFieldValue;

			hfPath.Load += hfPath_Load;

			string js = string.Format(@"<script language='javascript'>
                                            function deleteImage{0}(hfPath) {{
                                                path{0} = '_layouts/images/SPExtendedImageField/nopic.png';
                                                width{0} = '128px';
                                                height{0} = '128px';
                                                document.getElementById('{1}').src = path{0};
                                                document.getElementById('{1}').style.width = width{0};
                                                document.getElementById('{1}').style.height = height{0};
                                                document.getElementById(hfPath).value = '';
                                            }}
                                          </script>", guid.ToString("N"), guid);

			// Add Controls to the form. I haven't put a <a href... because when I click on it, it refresh the page and display [object], not with the span...
			Controls.Add(new LiteralControl(js));
			Controls.Add(hfPath);
			Controls.Add(new LiteralControl(string.Format(@"<span style='cursor:pointer;' class='ms-toolbar' onclick='javascript:window.open(""{0}"", ""ChoosePicture"", ""menubar=no, status=no, width=280, height=50"");'>{1}</span><br />
                                                            <span style='cursor:pointer;' class='ms-toolbar' onclick='javascript:deleteImage{2}(""{3}"");'>{4}</span><br /><br />
                                                            <img style='cursor:pointer;' id='{5}' src='' onclick='javascript:window.open(""{0}"", ""ChoosePicture"", ""menubar=no, status=no, width=280, height=50"");' /><br />",
															SPContext.Current.Web.Url + "/_layouts/SPExtendedImageField/ChoosePicture.aspx?GUID=" + guid + "&path=" + hfPath.UniqueID,
															SPUtility.GetLocalizedString("$Resources:ChoosePicture", "SPExtendedImageField", SPContext.Current.Web.Language),
															guid.ToString("N"), hfPath.ClientID,
															SPUtility.GetLocalizedString("$Resources:DeleteImage", "SPExtendedImageField", SPContext.Current.Web.Language),
															guid)));

			Controls.Add(new LiteralControl(string.Format(@"<script language=""javascript"">
                                                                document.getElementById('{0}').src = path{1};
                                                                document.getElementById('{0}').style.width = width{1};
                                                                document.getElementById('{0}').style.height = height{1};
                                                           </script>", guid, guid.ToString("N"))));

		}

		/// <summary>
		/// Loading of the hidden field
		/// </summary>
		void hfPath_Load(object sender, EventArgs e)
		{

			// If the field holds a value
			if (!string.IsNullOrEmpty(hfPath.Value))
			{

				// Get the picture library
				SPPictureLibrary pictureLibrary = (SPPictureLibrary)SPContext.Current.Site.RootWeb.Lists["Image Picker Picture List"];

				SPQuery query = new SPQuery
									{
										Query =
											string.Format(
											"<Where><Eq><FieldRef Name='FileLeafRef' /><Value Type='Text'>{0}</Value></Eq></Where>",
											hfPath.Value.Substring(hfPath.Value.LastIndexOf("/") + 1))
									};

				SPListItemCollection pictures = pictureLibrary.GetItems(query);

				if (pictures.Count > 0)
				{
					// Get the picture
					SPListItem picture = pictures[0];

					// Get the dimensions of the picture mminiature
					Dimension dimensions = Resizer.GetMiniature(int.Parse(picture["ImageWidth"].ToString()), int.Parse(picture["ImageHeight"].ToString()));

					// Create the three variable that holds the source and the dimension of the picture.
					// I done that because when the user try to save the item, if a required fill is not filled, it reloads the page and the picture doesn't appear anymore...
					Page.Response.Write(string.Format(@"<script language='javascript'>
                                                            var path{0} = '{1}';
                                                            var width{0} = '{2}px';
                                                            var height{0} = '{3}px';
                                                        </script>", Field.Id.ToString("N"), hfPath.Value, dimensions.Width, dimensions.Height));
				}
				else
					Page.Response.Write(string.Format(@"<script language='javascript'>
                                                          var path{0} = '_layouts/images/SPExtendedImageField/nopic.png';
                                                          var width{0} = '128px';
                                                          var height{0} = '128px';
                                                       </script>", Field.Id.ToString("N")));

			}
			// If the field doesn't hold a value, create the three variable for the nopic.png picture
			else
				Page.Response.Write(string.Format(@"<script language='javascript'>
                                                      var path{0} = '_layouts/images/SPExtendedImageField/nopic.png';
                                                      var width{0} = '128px';
                                                      var height{0} = '128px';
                                                   </script>", Field.Id.ToString("N")));
		}
	}
}

